import router from './index'
import { useAuthStore } from '@/stores/auth'
import { useUserStore } from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { handleSsoLogin } from '@/utils/sso'
import { asyncRoutes } from './async-routes'
import { RouteRecordRaw } from 'vue-router'

const whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const authStore = useAuthStore()
  const userStore = useUserStore()

  // 检查是否有SSO ticket
  const ticket = to.query.ticket as string
  if (ticket && !authStore.token) {
    try {
      await authStore.ssoLogin(ticket)
      next('/layout')
      return
    } catch (error) {
      next('/login')
      return
    }
  }

  if (authStore.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!authStore.user) {
        try {
          await authStore.getUserInfo()
          // 动态添加路由
          const accessRoutes = filterAsyncRoutes(asyncRoutes, authStore.permissions)
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })
          next({ ...to, replace: true })
        } catch (error) {
          await authStore.logout()
          next('/login')
        }
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

const generateAsyncRoutes = (permissions: string[]) => {
  const asyncRoutes = []
  
  // 根据权限动态生成路由
  if (permissions.includes('system:manage')) {
    asyncRoutes.push({
      path: '/system',
      component: () => import('@/views/system/index.vue'),
      children: [
        {
          path: 'user',
          component: () => import('@/views/system/user/index.vue'),
          meta: { permission: 'system:user' }
        },
        {
          path: 'role',
          component: () => import('@/views/system/role/index.vue'),
          meta: { permission: 'system:role' }
        }
      ]
    })
  }
  
  return asyncRoutes
}

const filterAsyncRoutes = (routes: RouteRecordRaw[], permissions: string[]) => {
  return routes.filter(route => {
    if (route.meta?.permission) {
      return permissions.includes(route.meta.permission)
    }
    return true
  })
} 